<!-- 添加推广链接 -->
<!-- 添加推广链接 -->
<template>
  <el-dialog
    v-model="dialogVisible"
    width="50%"
    top="10%"
    :title="action === 'edit' ? '编辑视频号' : action === 'add' ? '添加视频号' : ''"
    draggable
    appendToBody
    destroyOnClose
    lockScroll
    :closeOnClickModal="false"
  >
    <base-skeleton v-if="pageLoad.loadState === true" style="width: 100%; height: 100%; min-height: 420px; padding: 0 20px"></base-skeleton>
    <template v-else-if="pageLoad.loadState === false">
      <el-form ref="elFormRef" :validateOnRuleChange="false" :model="formData" :rules="rules" scrollToError :disabled="disabled">
        <div style="display: flex; gap: 20px">
          <div v-auto-animate style="flex: 1">
            <el-form-item label="微信视频号作者Id" labelWidth="10em" prop="wxFinderId">
              <el-input v-model="formData.wxFinderId" :maxlength="80" clearable placeholder="请输入微信视频号作者Id"></el-input>
            </el-form-item>
            <el-form-item label="视频号名称" labelWidth="10em" prop="wxFinderName">
              <el-input v-model="formData.wxFinderName" :maxlength="80" clearable placeholder="请输入视频号名称"></el-input>
            </el-form-item>
            <el-form-item label="部门" labelWidth="10em" prop="useOrigin">
              <box-from-border>
                <el-radio-group v-model="formData.useOrigin">
                  <el-radio label="投放部门" :value="1"></el-radio>
                  <el-radio label="星图部门" :value="2"></el-radio>
                </el-radio-group>
              </box-from-border>
            </el-form-item>
            <el-form-item label="投手名称" labelWidth="10em" prop="createName">
              <el-input v-model="formData.createName" :maxlength="80" clearable placeholder="请输入投手名称"></el-input>
            </el-form-item>
            <el-form-item labelWidth="10em" label="商品模板" prop="productTemplateId" @click="handleSelectTemplate(4)">
              <box-from-border isClick placeholder="请选择商品模版" :disabled="disabled" :text="formData.dramaFirstTemplate.templateName"></box-from-border>
            </el-form-item>
            <el-form-item label="选择短剧" labelWidth="10em" prop="drama">
              <bubble-select-local
                v-model="formData.drama"
                labelKey="dramaTitle"
                valueKey="dramaId"
                returnOriginal
                :axios="getDramaListAxios"
                placeholder="请选择短剧"
                @change="dramaChangeHandler"
              ></bubble-select-local>
            </el-form-item>
            <el-form-item label="单集解锁价格" labelWidth="10em" prop="price">
              <base-input-number v-model="formData.price" :max="100000" verify="add_int" placeholder="请输入单集解锁价格" clearable>
                <template #suffix>K币</template>
              </base-input-number>
            </el-form-item>
            <el-form-item label="起始付费集数" labelWidth="10em" prop="rechargeEpisodeNum">
              <base-input-number
                v-model="formData.rechargeEpisodeNum"
                verify="add_int_or_zero"
                placeholder="请输入从第几集开始付费(包含该集)"
                clearable
              ></base-input-number>
            </el-form-item>
          </div>
          <div style="flex: 1; overflow: hidden">
            <div class="content-vessel">
              <div class="content-box" @click="handleSelectTemplate(4)">
                <page-simulation-template
                  :selectIndex="formData.dramaFirstTemplate.selectIndex"
                  :templateProductList="formData.dramaFirstTemplate.productList"
                ></page-simulation-template>
                <div class="title-box">
                  <el-button style="width: 100%" :icon="IconPointer" type="primary">
                    {{ formData.productTemplateId ? '重选商品模版' : '选择商品模版' }}
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </div>
        <el-form-item v-if="!disabled" key="el-form-item-4" labelWidth="0em">
          <div style="width: 100%; padding-top: 20px">
            <el-button style="width: 100%" type="success" :disabled="loading" :loading="loading" @click="submit">保存</el-button>
          </div>
        </el-form-item>
      </el-form>
    </template>
    <base-empty
      v-else
      style="height: 100%"
      :description="pageLoad.description || ''"
      :imageSize="240"
      :loadState="pageLoad.loadState"
      :pageLoadButton="[{ text: '重新加载', callBack: getBaseDataAxios }]"
    ></base-empty>
    <page-select-template ref="pageSelectTemplateRef"></page-select-template>
  </el-dialog>
</template>

<script setup lang="ts">
  import type { FormInstance, FormRules } from 'element-plus';
  import { vAutoAnimate } from '@formkit/auto-animate/vue';
  import IconPointer from '~icons/ep/pointer';
  import {
    type BaseBackTemplate,
    type Drama,
    type Episode,
    type IaaBaseBackTemplate,
    type MpInfo,
    type ReferralLink,
    type ReferralRecord,
    type ReferralTemplate,
    type TemplateProductMarketingInfo,
    getDramaListAxios,
    getEpisodeListAxios,
    getMpInfoAxios,
    getTemplateProductByFinderId,
    tencentFinderRecordAdd,
    tencentFinderRecordUpdate,
  } from '@/api/marketing-management';
  import PageSelectTemplate from '@/components/page/page-select-template/page-select-template.vue';

  type $EditShowData = {
    /** 操作 */
    action: 'clone' | 'edit';
    referralRecord: ReferralRecord;
    /** 审核后的回调 */
    editCallBack?: () => void;
  };

  type $AddShowData = {
    /** 操作 */
    action: 'add';
    /** 审核后的回调 */
    addCallBack?: () => void;
  };

  type FormData = Omit<ReferralLink, 'dramaId' | 'episodeId' | 'productBackTemplateId'> & {
    dramaFirstTemplate: TemplateProductMarketingInfo;
    /** 短剧信息 */
    drama: Drama | undefined;
    /** 剧集信息 */
    episode: Episode | undefined;
    useOrigin: number | undefined;
  };
  const episodeList = ref<Episode[]>([]);

  const pageLoad = shallowReactive<$PageLoad>({ loadState: true, description: '' });

  let addCallBack: $AddShowData['addCallBack'] = undefined;
  let editCallBack: $EditShowData['editCallBack'] = undefined;

  const dialogVisible = ref(false);
  const elFormRef: Ref<FormInstance | null> = ref(null);
  const pageSelectTemplateRef: Ref<InstanceType<typeof PageSelectTemplate> | null> = ref(null);
  const action = ref<'add' | 'clone' | 'details' | 'edit'>();
  const loading = ref(false);
  const mpInfoLIst = shallowRef<MpInfo[]>([]);

  const disabled = computed(() => action.value === 'details');

  const formData = reactive<FormData>({
    wxFinderId: undefined,
    wxFinderName: undefined,
    createName: undefined,
    wxFinderRecordId: undefined,
    advertUnlock: 0,
    dramaFirstTemplate: {
      templateName: '',
      templateType: 4,
      selectIndex: 0,
      advertUnlock: 0,
      productList: [],
    },
    drama: undefined,
    episode: undefined,
    useOrigin: undefined,
  });
  /** IAP回传模版信息 */
  const iapBackTemplate = ref<BaseBackTemplate | undefined>(undefined);
  /** IAA回传模版信息 */
  const iaaBackTemplate = ref<IaaBaseBackTemplate | undefined>(undefined);

  const rules = computed(() => {
    const _rules: FormRules<FormData> = {
      wxFinderId: [{ required: true, type: 'string', message: '请输入微信视频号作者Id', trigger: ['blur', 'change'] }],
      wxFinderName: [{ required: true, type: 'string', message: '请输入视频号名称', trigger: ['blur', 'change'] }],
      createName: [{ required: true, type: 'string', message: '请输入投手名称', trigger: ['blur', 'change'] }],
      useOrigin: [{ required: true, type: 'number', message: '请选择部门', trigger: ['blur', 'change'] }],
      productTemplateId: [{ required: true, message: '请选择商品模板', trigger: ['blur', 'change'] }],
      drama: [{ required: true, type: 'object', message: '请选择短剧', trigger: ['blur', 'change'] }],
      episode: [{ required: true, type: 'object', message: '请选择剧集', trigger: ['blur', 'change'] }],
    };
    return _rules;
  });

  /**
   * 提交
   */
  async function submit() {
    try {
      await elFormRef.value?.validate();
      try {
        loading.value = true;
        const data: ReferralLink = {
          productTemplateId: formData.productTemplateId,
          wxFinderId: formData.wxFinderId,
          wxFinderName: formData.wxFinderName,
          createName: formData.createName,
          wxFinderRecordId: formData.wxFinderRecordId,
          dramaId: formData.drama?.dramaId,
          episodeId: formData?.episode?.episodeId,
          price: formData.price,
          rechargeEpisodeNum: formData.rechargeEpisodeNum,
          useOrigin: formData.useOrigin,
        };
        if (action.value === 'edit') {
          await tencentFinderRecordUpdate(data);
          typeof editCallBack === 'function' && editCallBack();
        } else {
          await tencentFinderRecordAdd(data);
          typeof addCallBack === 'function' && addCallBack();
        }
        loading.value = false;
        ElToast.success('添加成功');
        hide();
      } catch (error) {
        console.log('aaa====', error);
        loading.value = false;
        ElToast.error(error.msg || '提交失败，-BD001');
      }
    } catch (error) {
      ElToast.error('提交失败，请完善表单，-BD002');
    }
  }

  /** 短剧变更填充默认剧集 */
  async function dramaChangeHandler(val: Drama) {
    try {
      formData.episode = undefined;
      const { data } = await getEpisodeListAxios({ dramaId: val.dramaId });
      episodeList.value = data ?? [];
      console.log('data', data);
      if (data.length) {
        formData.episode = data[0];
      }
    } catch (error) {}
  }
  const initFormData = () => {
    iapBackTemplate.value = undefined;
    iaaBackTemplate.value = undefined;
    formData.wxFinderId = undefined;
    formData.wxFinderName = undefined;
    formData.createName = undefined;
    formData.wxFinderRecordId = undefined;
    formData.episode = undefined;
    formData.drama = undefined;
    formData.useOrigin = undefined;
    formData.price = undefined;
    formData.rechargeEpisodeNum = undefined;
    formData.advertUnlock = 0;
    formData.dramaFirstTemplate = {
      templateName: '',
      templateType: 4,
      selectIndex: 0,
      advertUnlock: 0,
      productList: [],
    };
  };

  /**
   * 显示
   */
  function show(data: any) {
    action.value = data.action;
    initFormData();
    if (data.action === 'edit' || data.action === 'clone' || data.action === 'details') {
      formData.productTemplateId = data.referralRecord.productTemplateId || undefined;
      formData.wxFinderId = data.referralRecord.wxFinderId || undefined;
      formData.wxFinderName = data.referralRecord.wxFinderName || undefined;
      formData.createName = data.referralRecord.createName || undefined;
      formData.wxFinderRecordId = data.referralRecord.wxFinderRecordId || undefined;
      formData.price = data.referralRecord.price || undefined;
      formData.rechargeEpisodeNum = data.referralRecord.rechargeEpisodeNum || undefined;
      formData.useOrigin = data.referralRecord.useOrigin || undefined;
    }
    if (data.referralRecord?.dramaId && data.referralRecord?.dramaTitle) {
      formData.drama = { dramaId: data.referralRecord.dramaId, dramaTitle: data.referralRecord.dramaTitle };
    }
    if (data.referralRecord?.episodeId) {
      formData.episode = { episodeId: data.referralRecord.episodeId, episodeTitle: `第${(data.referralRecord.episodeSeq || 0) + 1}集` };
    }
    addCallBack = 'addCallBack' in data && typeof data.addCallBack === 'function' ? data.addCallBack : undefined;
    editCallBack = 'editCallBack' in data && typeof data.editCallBack === 'function' ? data.editCallBack : undefined;

    dialogVisible.value = true;

    getBaseDataAxios();
  }

  /**
   * 隐藏
   */
  function hide() {
    dialogVisible.value = false;
  }

  /** 请求 */
  async function getBaseDataAxios() {
    try {
      pageLoad.loadState = true;

      const res = await Promise.all(
        formData.wxFinderRecordId ? [getMpInfoAxios(), getTemplateProductByFinderId({ wxFinderRecordId: formData.wxFinderRecordId })] : [getMpInfoAxios()]
      );
      mpInfoLIst.value = res[0].data || [];
      if (res[1]) {
        formData.dramaFirstTemplate = {
          ...res[1].data,
          productList: res[1].data.productList || [],
          templateName: res[1].data.templateName || '',
          templateType: res[1].data.templateType || 4,
          selectIndex: res[1].data.selectIndex || 0,
          advertUnlock: res[1].data.advertUnlock || 0,
        };
      }

      const mpInfo = mpInfoLIst.value.find((item) => item.investmentId === formData.investmentId);
      formData.iaaFlag = mpInfo?.iaaFlag || 0;

      pageLoad.loadState = false;
    } catch (error) {
      pageLoad.loadState = 'err';
      pageLoad.description = String((error as Record<string, unknown>).msg || '') || '获取数据失败';
    }
  }

  /**
   * 选择模板
   */
  function handleSelectTemplate(templateType: 1 | 2 | 4) {
    if (!disabled.value) {
      pageSelectTemplateRef.value?.show({
        templateType,
        selectCallBack(res: ReferralTemplate) {
          if (formData.productTemplateId !== res.productTemplateId) {
            formData.dramaFirstTemplate = res;
            formData.productTemplateId = res.productTemplateId!;
            formData.advertUnlock = res.advertUnlock;
            iapBackTemplate.value = undefined;
          }
        },
      });
    }
  }

  defineExpose({ show, hide });
</script>

<style scoped lang="scss">
  .content-vessel {
    display: grid;
    grid-template-columns: repeat(auto-fill, 259px);
    gap: 15px;
    width: 100%;

    .content-box {
      overflow: hidden;
      cursor: pointer;
      background: $c-bg-block;
      border-radius: 10px;
      box-shadow: var(--my-box-shadow-fill);

      .title-box {
        box-sizing: border-box;
        display: flex;
        align-items: center;
        justify-content: space-between;
        width: 100%;
        padding: 10px;
      }
    }
  }
</style>
